//
//  QWMineController.m
//  qwm
//
//  Created by kevin on 2023/3/23.
//

#import "QWMineController.h"
#import "QWMineInfoView.h"
#import "QWLoginController.h"
#import "QWMineMenusCell.h"
#import "QWMyMenusCell.h"
#import "QWButtonView.h"
#import "QWFeedbackController.h"
#import "QWTipsAlertController.h"
#import "QWAboutUsController.h"
#import "QWMineInfoController.h"
#import "EaseGroupMemberAttributesCache.h"
#import "QWWebviewController.h"

@interface QWMineController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) QWMineInfoView *mineInfoView;
@property (nonatomic, strong) NSArray *menusArr;
@property (nonatomic, strong) QWMyMenusCell *menusCell;
@end

@implementation QWMineController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [_tableView reloadData];
    
    if(AppProfile.meMenus == nil){
        //菜单
        [self fetchMenusOnMePage];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的";
        
    self.menusArr = @[
    @{
        @"name": @"后续反馈",
        @"icon": @"ic_feedback.png",
    },
    @{
        @"name": @"关于我们",
        @"icon": @"ic_about.png",
    },
    @{
        @"name": @"当前版本",
        @"icon": @"ic_version.png",
    }];
    [self tableView];
    [self mineInfoView];
}

#pragma mark- 个人信息
-(QWMineInfoView *)mineInfoView
{
    if (!_mineInfoView) {
        _mineInfoView =[[QWMineInfoView alloc]init];
        [self.view addSubview:_mineInfoView];
        [_mineInfoView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view);
            make.right.equalTo(self.view);
            make.top.equalTo(self.view);
            make.height.mas_equalTo(Mine_Header_Height);
        }];
        
        __weak __typeof(self) weakSelf = self;
        _mineInfoView.mineInfoBlock = ^(BOOL isLogin) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            if(isLogin){
                [strongSelf jumpToMineInfo];
            }else{
                [strongSelf jumpToLogin];
            }
        };
    }
    return _mineInfoView;
}

- (UITableView *)tableView{
    if(!_tableView){
        _tableView =[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.contentInset=UIEdgeInsetsMake(Mine_Header_Height, 0, 0, 0);
        _tableView.estimatedRowHeight = 400;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedSectionFooterHeight=0;
        _tableView.estimatedSectionHeaderHeight=0;
        _tableView.showsVerticalScrollIndicator=NO;
        _tableView.showsHorizontalScrollIndicator=NO;
        
        _tableView.delegate =self;
        _tableView.dataSource =self;
        
        [_tableView registerNib:[UINib nibWithNibName:@"QWMineMenusCell" bundle:nil] forCellReuseIdentifier:@"QWMineMenusCell"];
//        [_tableView registerNib:[UINib nibWithNibName:@"ZBMineHomeCell" bundle:nil] forCellReuseIdentifier:@"ZBMineHomeCell"];
        [_tableView registerClass:[QWMyMenusCell class] forCellReuseIdentifier:@"QWMyMenusCell"];
        _tableView.backgroundColor=[UIColor whiteColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        
    }
    return _tableView;
}


#pragma mark- UITableViewDelegate,UITableViewDataSource


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0000001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return section==0?0.0000001:85.0;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return section==0? AppProfile.meMenus?1:0:self.menusArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        QWMyMenusCell *cell =[tableView dequeueReusableCellWithIdentifier:@"QWMyMenusCell"];
        _menusCell = cell;
        cell.menuItemClickBlock = ^(QWMyMenuItem * _Nonnull menuItem) {
            [self menuButtonClick:menuItem];
        };
        return cell;
    }else{
        QWMineMenusCell *cell =[tableView dequeueReusableCellWithIdentifier:@"QWMineMenusCell"];
        [cell changeRightShow:indexPath.row == 2];
        NSDictionary *dic = self.menusArr[indexPath.row];
        cell.iconImageView.image = [UIImage imageNamed:dic[@"icon"]];
        cell.nameLabel.text = dic[@"name"];
        if(indexPath.row == 2){
            cell.desLabel.text = [[QWCommonMethod Instance] currentVersion];
        }
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if(indexPath.section == 1){
        if(indexPath.row == 0){
            if([AppProfile isLoginedAlert]){
                QWFeedbackController *fdvc = [[QWFeedbackController alloc]init];
                fdvc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:fdvc animated:YES];
            }
        }
        if(indexPath.row == 1){
            QWAboutUsController *aboutUsVC = [[QWAboutUsController alloc]init];
            aboutUsVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:aboutUsVC animated:YES];
        }
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    QWButtonView *view = [[QWButtonView alloc]init];
    view.superVC = self;
    [view changeButtonState: AppProfile.qaUserInfo != nil];
    __weak __typeof(self) weakSelf = self;
    view.logoutBlock = ^{
        NSLog(@"退出登录");
        [AppProfile clearUserInfo];
        [[EMClient sharedClient] logout:YES completion:^(EMError * _Nullable aError) {
            [[EaseGroupMemberAttributesCache shareInstance] removeAllCaches];
            if(!aError){
                EMDemoOptions *options = [EMDemoOptions sharedOptions];
                options.isAutoLogin = NO;
                options.loggedInUsername = @"";
                options.loggedInPassword = @"";
                [options archive];
                [[NSNotificationCenter defaultCenter] postNotificationName:ACCOUNT_LOGIN_CHANGED object:@NO];
            }
        }]; //环信登出
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf.tableView reloadData];
        [[NSNotificationCenter defaultCenter] postNotificationName:QWLogin_Change_State object:nil];
    };
    return  view;
}


#pragma mark- 个人信息view移动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat scroll_y=-scrollView.contentOffset.y;
    if (scroll_y <= Mine_Header_Height) {
        if(scroll_y<= [UIDevice safeDistanceTop]){
            [_mineInfoView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo([UIDevice safeDistanceTop]-Mine_Header_Height);
                make.height.mas_equalTo(Mine_Header_Height);
            }];
        }else{
            [_mineInfoView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(scroll_y-Mine_Header_Height);
                make.height.mas_equalTo(Mine_Header_Height);
            }];
        }
    }else
    {
        [_mineInfoView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view);
            make.height.mas_equalTo(scroll_y<=Mine_Header_Height?Mine_Header_Height:scroll_y);
        }];
    }
}

#pragma mark - 菜单按钮-跳转
- (void)menuButtonClick:(QWMyMenuItem *)menuItem{
    NSString *url = menuItem.imgTarget;
    if(!IsStringEmpty(url) && [AppProfile isLoginedAlert]){
        [self jumToWebView:url];
    }
}

#pragma mark - webview - 跳转
- (void)jumToWebView:(NSString *)url{
    QWWebviewController *webviewVC =[[QWWebviewController alloc]init];
    webviewVC.url = url;
    webviewVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webviewVC animated:YES];
}

#pragma mark - 登录 - 跳转
- (void)jumpToLogin{
    QWLoginController *loginVC =[[QWLoginController alloc]init];
    [loginVC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:loginVC animated:YES];
}

#pragma mark - 个人信息 - 跳转
- (void)jumpToMineInfo{
    QWMineInfoController *vc =[[QWMineInfoController alloc]init];
    [vc setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 我的-菜单数据-在此再次请求数据
- (void)fetchMenusOnMePage{
    HXGetRequest * request = [[HXGetRequest alloc] initWithRequestUrl:URL_MENUS_ON_ME_PAGE argument:@{}];
    [request startWithCompletionBlockWithSuccess:^(__kindof HXRequest *request, NSDictionary *result, BOOL success) {
        if(success && result != nil ){
            AppProfile.meMenus = [QWMeMenus mj_objectWithKeyValues:result];
            [self->_menusCell loadData];
            [self->_tableView reloadData];
        }
    } failure:^(__kindof HXRequest *request, NSString *errorInfo) {
    
    }];
}

@end
